#ifndef CLOCOLIPS_H
#define CLOCOLIPS_H

#include <QThread>
#include <QFile>
#include <QSocketNotifier>
#include <QReadWriteLock>
#include <QUdpSocket>
#include "knx/cmei.h"

class CLocolIPS : public QThread
{
    Q_OBJECT
public:
    explicit CLocolIPS(QObject *parent = 0);

    bool init;
    static bool gSendRecord;

    void resetChannel();
    _u8 calc_onebyte_crc(_u8 *buff,_u8 size);

    _int32 ttg_read_status(_u8 addr[]);
    _int32 ttg_write_device(_u8 addr[2],_u8 value_type,_u8 *data,_u32 len);

    bool ttg_data_crc_verify(_u8 *data,_u8 size);
    void ttg_data_analyze(_u8 msg[],_u8 msg_len);

    bool registeObject(void *devObj,void *userdata);
    bool unRegisterObject(void *devObj,void *userdata);
    void unRegisterAll();

    _int32 ttg_cmei_data_analyze(_u8 msg[],_u8 msg_len);
    QList<QByteArray> splitDatagram(unsigned char *data,int size);

signals:
    void s_gateWayConnectState(int state);
    void s_valueNotify(void *devObj,QByteArray value,void *userdata);
    void s_valueNotify_debug(void *devObj,QString value,void *userdata);
    void s_recordMsg(QString msg );

public slots:
    void readDataChannel(int fd);
    void doReadDevice(QByteArray addr2bytes);
    void doWriteDevice(QByteArray addr2bytes,int data_type,QByteArray data);
    void doRegistObject(void *dev,void *userdata);
    void doReadLocalUdpData();

protected:
    void run();

    void updateIpsState(int state);
    void set_package_length(char *buff_head,_u8 length);
    unsigned int set_msg_header(char *buff);

    _u8 package_cmei_msg_ttg(_u8 msg[],_u8 controlField1,_u8 addr[2],_u8 *value,_u8 size);
    int ttg_send_msg(char *buff,int size);

    void ttg_data_unpackage(_u8 *cemi_data,int size,_u8 *decode_buf);    
    unsigned short ttg_data_package(_u8 addr[2],_u8 *value,char value_len,_u8 *buff);
    void data_analyze(QByteArray bytes,QString peerIP,unsigned short peerPort);

    _int32 message_device_data_handle(DEVICE_OBJECT *data,_u8 *value,_u8 value_len);
    _int32 routing_indication_recv_analyze(_u8 data[],_u32 data_type,_u8 *operation_type,
                                           _u8 **ret_value,_u8 *ret_len);

    QReadWriteLock lock;

    QSocketNotifier *_knxRcvnotifier;
    int _readFd,_writeFd;

    QMultiMap<QByteArray, DEVICE_OBJECT *> _registersMap;

    QUdpSocket *localControl;
    QHostAddress peerHost;
    int peerPort;
};

#endif // CLOCOLIPS_H
